package com.website.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.website.common.controller.BaseController;
import com.website.common.warpper.ResultMap;
import com.website.system.dao.ComputerDetailsMapper;
import com.website.system.model.Computer;
import com.website.system.model.ComputerDetails;
import com.website.system.model.vo.ComputerVo;
import com.website.system.service.ComputerDetailsService;
import com.website.system.service.ComputerService;
import com.website.system.utils.HandlingTime;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("manage/computerDetails")
public class ComputerDetailsController extends BaseController {

    @Resource
    private ComputerDetailsService service;

    @Resource
    private ComputerService computerService;

    @Resource
    private ComputerDetailsMapper computerDetailsMapper;

    @RequestMapping("")
    public String find() {
        return "manage/computerDetails";
    }

    /**
     * 条件分页查询
     */
    @HandlingTime
    @ResponseBody
    @RequestMapping("/findByCon")
    public ResultMap findByCon(@RequestParam Integer page, @RequestParam Integer limit, @RequestParam(required = false) String content) {
        ResultMap<List<ComputerVo>> resultMap = new ResultMap<>(SUCCESS_CODE, SUCCESS_MSG, null, null);
        Page<ComputerDetails> pageInfo = new Page<>(page, limit);
        Wrapper<ComputerDetails> wrapper = new EntityWrapper<>();
        wrapper = content == null ? wrapper : wrapper.like("dname", content);
        List<ComputerDetails> clist = service.selectPage(pageInfo, wrapper.orderBy("id", true)).getRecords();
        resultMap.setCount(service.selectCount(wrapper));
        List<ComputerVo> voList = new ArrayList<>();
        for (ComputerDetails computerDetails : clist) {
            ComputerVo computerVo = new ComputerVo();
            Computer computer = computerService.selectById(computerDetails.getPid());
            computerVo.setId(computerDetails.getId());
            computerVo.setPid(computerDetails.getPid());
            computerVo.setDname(computerDetails.getDname());
            computerVo.setDtype(computerDetails.getDtype());
            computerVo.setColor(computerDetails.getColor());
            computerVo.setCreatTime(computerDetails.getCreateTime());
            computerVo.setShellTime(computerDetails.getShellTime());
            computerVo.setPicture(computerDetails.getPicture());
            computerVo.setName(computer.getName());
            voList.add(computerVo);
        }
        resultMap.setData(voList);
        return resultMap;
    }

    @RequestMapping("/addComputerDetails")
    public String toAddComputerDetails() {
        return "manage/computerDetailsAdd";
    }

    /**
     * 添加信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/computerDetailsAdd", method = RequestMethod.POST)
    public String toComputerDetailsAdd(ComputerDetails computerDetails) {
        try {
            service.insert(computerDetails);
            return SUCCESS_MSG;
        } catch (Exception e) {
            return ERROR_MSG;
        }
    }

    /**
     * 修改页面
     */
    @RequestMapping("/update/{id}")
    public String getComputerDetails(Model model, @PathVariable Integer id) {
        ComputerDetails computerDetails = service.selectById(id);
        computerDetails.setDname(computerDetails.getDname().replaceAll("\"", "&quot;"));
        model.addAttribute("computerDetails", computerDetails);
        Computer computer = computerService.selectById(computerDetails.getPid());
        model.addAttribute("computer", computer);
        return "manage/computerDetailsUpdate";
    }

    /**
     * 修改保存
     */
    @ResponseBody
    @RequestMapping("/computerDetailsUpdate")
    public String toUpdateComputerDetails(@ModelAttribute ComputerDetails computerDetails) {
        service.updateById(computerDetails);
        return SUCCESS_MSG;
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping(value = "/deleteComputerDetails", method = RequestMethod.POST)
    public String deleteComputerDetails(@Param("id") Integer id) {
        service.deleteById(id);
        return SUCCESS_MSG;
    }

    /**
     * 加载电脑类别
     */
    @ResponseBody
    @RequestMapping(value = "/computerType", method = RequestMethod.POST)
    public List<Computer> computerType() {
        Wrapper<Computer> cw = new EntityWrapper<>();
        return computerService.selectList(cw);
    }

    /**
     * 跳转页面
     */
    @RequestMapping("/toComputerDetailsImg/{id}")
    public String toComputerDetailsImg(Model model, @PathVariable Integer id) {
        ComputerDetails computerDetails = service.selectById(id);
        computerDetails.setDname(computerDetails.getDname().replaceAll("\"", "&quot;"));
        model.addAttribute("computerDetails", computerDetails);

        return "manage/computerDetailsUpdateImg";
    }

    /**
     * 修改图片
     */
    @ResponseBody
    @RequestMapping("/computerDetailsUpdateImg")
    public String computerDetailsUpdateImg(ComputerDetails computerDetails) {
        computerDetails.setPicture("files/image/" + computerDetails.getPicture() + ".jpg");
        service.updateById(computerDetails);
        return SUCCESS_MSG;
    }

    /**
     * 导出excel表格
     * @return
     */
    @RequestMapping(value = "/exportComputer", method = RequestMethod.GET)
    public void exportComputer(HttpServletResponse response) throws IOException {
        List<ComputerDetails> users = service.findByCon();

        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFSheet sheet = wb.createSheet("获取excel测试表格");

        HSSFRow row = null;

        row = sheet.createRow(0);//创建第一个单元格
        row.setHeight((short) (26.25 * 20));
        row.createCell(0).setCellValue("电脑信息列表");//为第一行单元格设值

        /*为标题设计空间
         * firstRow从第1行开始
         * lastRow从第0行结束
         *
         *从第1个单元格开始
         * 从第3个单元格结束
         */
        CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
        sheet.addMergedRegion(rowRegion);

      /*CellRangeAddress columnRegion = new CellRangeAddress(1,4,0,0);
      sheet.addMergedRegion(columnRegion);*/


        /*
         * 动态获取数据库列 sql语句 select COLUMN_NAME from INFORMATION_SCHEMA.Columns where table_name='user' and table_schema='test'
         * 第一个table_name 表名字
         * 第二个table_name 数据库名称
         * */
        row = sheet.createRow(1);
        row.setHeight((short) (22.50 * 20));//设置行高
        row.createCell(0).setCellValue("序号");//为第一个单元格设值
        row.createCell(1).setCellValue("类别名称");//为第二个单元格设值
        row.createCell(2).setCellValue("名称");//为第三个单元格设值
        row.createCell(3).setCellValue("颜色");
        row.createCell(4).setCellValue("生产日期");
        row.createCell(5).setCellValue("图片");
        row.createCell(6).setCellValue("出售日期");

        for (int i = 0; i < users.size(); i++) {
            row = sheet.createRow(i + 2);
            ComputerDetails user = users.get(i);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getPid());
            row.createCell(2).setCellValue(user.getDname());
            row.createCell(3).setCellValue(user.getColor());
            row.createCell(4).setCellValue(user.getCreateTime());
            row.createCell(5).setCellValue(user.getPicture());
            row.createCell(6).setCellValue(user.getShellTime());

        }
        sheet.setDefaultRowHeight((short) (16.5 * 20));
        //列宽自适应
        for (int i = 0; i <= 13; i++) {
            sheet.autoSizeColumn(i);
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment;filename=computer.xls");//默认Excel名称
        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 导入excel表格
     * @param file
     * @param session
     * @return
     */
    @RequestMapping(value = "/importComputer")
    public String importComputer(@RequestParam(value = "filename") MultipartFile file, HttpSession session) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        System.out.println("上传文件名称"+fileName);
        try {
            a = service.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/manage/computerDetails";
    }
}

